import type { ComponentStyleIdType } from '../../../../types/interfaces'
import type {
  DiscussionAnalyticsConfig,
  DiscussionAnalyticsData,
  DiscussionAnalyticsPlatformConfig,
  DiscussionCommentData,
  DiscussionDuration,
  DiscussionRoleBasedData,
  DiscussionTimeDistribution,
  DiscussionTimeMetrics,
  DiscussionUserRolesDistribution,
  DiscussionUserStats,
} from './types'
import { BaseModule } from '../../../../lib/abstract'
import { PageHandler } from '../../../../lib/page_handler'
import { GreasyForkPageType } from '../../../../lib/page_handler/platform/greasyfork/types'
import { ToolKit } from '../../../../lib/utils/toolkit'
import {
  BUTTON_TEMPLATE_STYLES,
  ComponentStyleId,
  HOSTNAME,
  logger,
  SUPPORTED_PLATFORMS,
  TIME_UNITS,
} from '../../../../types/constants'
import { SYMBOLS } from '../../../../types/interfaces'
import { ConfigManager } from '../../../config_manager'
import { DiscussionAnalyticsScore } from './service/score'
import { DiscussionAnalyticsUI } from './service/ui'
import {
  DiscussionActivityLevel,
  DiscussionUserRole,
} from './types'

interface Config {
  enabled?: boolean
  debug: boolean
  showUserRankings?: boolean
  showTimeDistribution?: boolean
  maxUsersDisplay?: number
}

/**
 * 讨论分析（评论数量统计、参与者分析、角色识别、时间分布、活跃度排名）
 * 测试链接：
 * 1）https://greasyfork.org/zh-CN/scripts/553387-youtube-playback-plox/discussions/313165
 * 2）https://greasyfork.org/zh-CN/discussions/greasyfork/278992
 */
export class DiscussionAnalytics extends BaseModule {
  // @Decorators.Identity
  readonly id: string = 'discussion_analytics'

  get name(): ComponentStyleIdType {
    return 'DiscussionAnalytics'
  }

  // @Decorators.PublicState
  isInitialized: boolean = false
  private static instance: DiscussionAnalytics
  // @Decorators.InheritedConfig
  readonly styleId: string = ComponentStyleId[this.name]
  readonly supportedPlatforms: string[] = ConfigManager.getInstance().moduleSupportedPlatforms(this.name)
  // @Decorators.CoreDependency
  private uiService: DiscussionAnalyticsUI = DiscussionAnalyticsUI.getInstance(this)
  private scoreService: DiscussionAnalyticsScore = DiscussionAnalyticsScore.getInstance(this)
  // @Decorators.UIElement
  private readonly BUTTON_ID: string = 'discussion-analytics-trigger'
  // @Decorators.Config
  get currentConfig(): DiscussionAnalyticsConfig | undefined {
    return this.getCurrentConfig()
  }

  // @Decorators.TemporaryState
  // 状态管理
  private buttonElement: JQuery<HTMLElement> | null = null
  private isAnalysisRunning: boolean = false
  private isDashboardRendered: boolean = false
  // 数据存储
  private commentsData: DiscussionCommentData[] = []
  analyticsData: DiscussionAnalyticsData | null = null
  refreshTimer: number | null = null

  config: Config = {
    enabled: true,
    debug: true,
    showUserRankings: true,
    showTimeDistribution: true,
    maxUsersDisplay: 10,
  }

  /**
   * 获取单例实例
   */
  public static getInstance(): DiscussionAnalytics {
    if (!DiscussionAnalytics.instance) {
      DiscussionAnalytics.instance = new DiscussionAnalytics()
    }
    return DiscussionAnalytics.instance
  }

  core(): void {
    this.loadConfig()

    if (!this.config.enabled)
      return

    this.setupAnalysis()

    // 注册样式
    this.registerStyle(this.styleId, this.getStyles())
  }

  onToggleCallback(_id: string, checked: boolean): void {
    super.onToggleCallback(_id, checked)
  }

  handleCleanupEventListeners(): void {
    // 移除按钮点击事件
    this.buttonElement?.off('click')
    // 移除点击外部关闭事件
    this.uiService.clickOutsideHandler?.destroy()
  }

  handleCleanupStyles(): void {
    this.unregisterStyle(this.styleId)
  }

  handleCleanupOthers(): void {
    // 销毁所有图表
    this.uiService.charts.forEach(chart => chart.destroy())
    this.uiService.charts.clear()
    this.uiService.selectInstance?.destroy()

    // 清理定时器
    if (this.refreshTimer) {
      clearInterval(this.refreshTimer)
      this.refreshTimer = null
    }

    this.uiService.isDashboardVisible = false
  }

  /**
   * 获取当前页面的配置
   */
  getCurrentConfig(): DiscussionAnalyticsConfig | undefined {
    const config: DiscussionAnalyticsPlatformConfig = {
      [SUPPORTED_PLATFORMS.GREASY_FORK]: {
        [GreasyForkPageType.SCRIPT_DISCUSSION]: {
          selector: '#script-content > .comment',
          authorName: '.avatar-name span',
          authorUrl: '.avatar-name',
          avatar: '.avatar',
          postTime: '.comment-meta .comment-meta-item:contains("发布于") relative-time[datetime]',
          roleIndicator: {
            originalPoster: '.badge-original-poster',
            author: '.badge-author',
            admin: '.badge-moderator',
            deletedUser: '.deleted-user-wrapper',
          },
          button: '.discussion-header .discussion-actions',
        },
        [GreasyForkPageType.DISCUSSIONS_DETAIL]: {
          selector: '.text-content > .comment',
          authorName: '.avatar-name span',
          authorUrl: '.avatar-name',
          avatar: '.avatar',
          postTime: '.comment-meta .comment-meta-item:contains("发布于") relative-time[datetime]',
          roleIndicator: {
            originalPoster: '.badge-original-poster',
            author: '.badge-author',
            admin: '.badge-moderator',
            deletedUser: '.deleted-user-wrapper',
          },
          button: '.discussion-header .discussion-actions',
        },
      },
    }

    const currentConfig = config[HOSTNAME]?.[PageHandler.getCurrentPageType()]

    if (!currentConfig) {
      logger.warn(`[${this.name}] 未找到当前页面类型的配置`)
    }

    return currentConfig
  }

  setupAnalysis(): void {
    logger.important(`[${this.name}] 初始化讨论分析`)
    this.renderControlButton()
  }

  /**
   * 渲染控制按钮
   */
  renderControlButton(): void {
    if (!this.currentConfig)
      return

    const container = $(this.currentConfig.button)

    if (!container) {
      logger.warn(`[${this.name}] 未找到按钮容器，无法渲染控制按钮`)
      return
    }

    if (container.find(`#${this.BUTTON_ID}`).length > 0)
      return

    this.buttonElement = $(`<button id="${this.BUTTON_ID}">${SYMBOLS.UI.CHART} 讨论分析</button>`)
    container.prepend(this.buttonElement)

    this.buttonElement.on('click', this.handleButtonClick.bind(this))
    this.tracker.creation(this.buttonElement)

    ToolKit.browser.platform.markProjectElement(this.buttonElement)
  }

  /**
   * 处理按钮点击事件
   */
  private handleButtonClick(): void {
    if (this.isAnalysisRunning) {
      logger.debug(`[${this.name}] 分析正在进行中，跳过重复执行`)
      return
    }

    if (this.isDashboardRendered) {
      logger.debug(`[${this.name}] 看板已显示，切换显示状态`)
      this.uiService.toggleDashboard()
      return
    }

    this.executeAnalysis()
  }

  /**
   * 执行分析
   */
  private executeAnalysis(): void {
    this.isAnalysisRunning = true

    try {
      // 检查是否已经有数据，避免重复分析
      if (!this.analyticsData || this.commentsData.length === 0) {
        this.collectDiscussionData()
        this.analyzeData()
      }
      else {
        logger.debug(`[${this.name}] 使用缓存数据，跳过数据收集`)
      }

      // 渲染看板
      this.uiService.renderDashboard()
      this.isDashboardRendered = true

      logger.info(`[${this.name}] 分析完成并显示看板`)
    }
    catch (error: any) {
      logger.error(`[${this.name}] 分析执行失败`, error)
    }
    finally {
      this.isAnalysisRunning = false
    }
  }

  /**
   * 收集讨论数据
   */
  collectDiscussionData(): void {
    this.commentsData = this.extractCommentsData(this.currentConfig!)

    logger.info(`[${this.name}] 收集到 ${this.commentsData.length} 条评论数据`)

    if (this.config.debug) {
      logger.info(`[${this.name}] 评论数据收集完成`, this.commentsData)
    }
  }

  /**
   * 从 DOM 提取评论数据
   */
  private extractCommentsData(config: DiscussionAnalyticsConfig): DiscussionCommentData[] {
    const comments: DiscussionCommentData[] = []

    $(config.selector).each((index, element) => {
      const $element = $(element)
      const id = $element.attr('id') || `comment-${index}`

      try {
        const commentData: DiscussionCommentData = {
          id,
          floorNumber: index + 1,
          user: {
            name: $element.find(config.authorName).text().trim(),
            url: $element.find(config.authorUrl).attr('href') || '',
            avatar: $element.find(config.avatar).attr('src') || '',
            isOriginalPoster: $element.find(config.roleIndicator.originalPoster).length > 0,
            isAuthor: $element.find(config.roleIndicator.author).length > 0,
            isAdmin: $element.find(config.roleIndicator.admin).length > 0,
            isDeletedUser: $element.find(config.roleIndicator.deletedUser).length > 0,
          },
          timestamp: $element.find(config.postTime).attr('datetime') || '',
          timestampMs: ToolKit.time.parseTimestamp($element.find(config.postTime).attr('datetime')),
          role: this.determineUserRole($element, config.roleIndicator),
        }

        comments.push(commentData)
      }
      catch (error) {
        logger.warn(`[${this.name}] 提取评论数据失败`, {
          id,
          error,
        })
      }
    })

    return comments
  }

  /**
   * 确定用户角色
   */
  private determineUserRole($element: JQuery<HTMLElement>, roleIndicator: any): DiscussionUserRole {
    if ($element.find(roleIndicator.originalPoster).length > 0)
      return DiscussionUserRole.OriginalPoster

    if ($element.find(roleIndicator.admin).length > 0)
      return DiscussionUserRole.Admin

    if ($element.find(roleIndicator.author).length > 0)
      return DiscussionUserRole.Author

    if ($element.find(roleIndicator.deletedUser).length > 0)
      return DiscussionUserRole.DeletedUser

    return DiscussionUserRole.RegularUser
  }

  /**
   * 分析数据
   */
  analyzeData(): void {
    if (this.commentsData.length === 0) {
      logger.warn(`[${this.name}] 未收集到评论数据，无法分析`)
      return
    }

    const userStats = this.calculateUserStats()
    const timeDistribution = this.calculateTimeDistribution()
    const activityPeaks = this.calculateActivityPeaks()
    const roleBasedData = this.calculateRoleBasedData()
    const timeMetrics = this.calculateTimeMetrics()

    this.analyticsData = {
      totalComments: this.commentsData.length,
      uniqueParticipants: userStats.length,
      userRoles: this.calculateUserRoles(),
      timeDistribution,
      userRankings: userStats
        // 注销用户没有名称，需要过滤掉
        .filter(peak => peak.commentCount > 0 && peak.name)
        .sort((a, b) => {
        // 多条件排序
          if (a.commentCount !== b.commentCount) {
            return b.commentCount - a.commentCount // 评论数量降序
          }

          return a.firstCommentTime - b.firstCommentTime // 首次评论时间升序
        })
        .slice(0, this.config.maxUsersDisplay || 10),
      activityPeaks,
      roleBasedData,
      averageCommentsPerUser: this.commentsData.length / userStats.length,
      mostActiveUser: this.calculateMostActiveUser(userStats),
      discussionDuration: this.calculateDiscussionDuration(),
      timeMetrics,
    }

    this.analyticsData.heatScore = this.scoreService.calculateHeatScore()
    this.analyticsData.heatColor = this.scoreService.getHeatColor(this.analyticsData.heatScore)
    this.analyticsData.heatIcon = this.scoreService.getHeatIcon(this.analyticsData.heatScore)

    if (this.config.debug) {
      logger.info(`[${this.name}] 评论数据分析完成`, this.analyticsData)
    }
  }

  /**
   * 计算用户统计数据
   */
  private calculateUserStats(): DiscussionUserStats[] {
    const userMap = new Map<string, DiscussionUserStats>()

    this.commentsData.forEach((comment) => {
      const { name, url, avatar } = comment.user

      if (!userMap.has(name)) {
        userMap.set(name, {
          name,
          url,
          avatar,
          role: comment.role,
          firstCommentTime: comment.timestampMs,
          lastCommentTime: comment.timestampMs,
          floorNumbers: [],
          commentCount: 0,
        })
      }

      const userStats = userMap.get(name)!

      userStats.floorNumbers.push(comment.floorNumber)
      userStats.commentCount++
      userStats.firstCommentTime = Math.min(userStats.firstCommentTime, comment.timestampMs)
      userStats.lastCommentTime = Math.max(userStats.lastCommentTime, comment.timestampMs)
    })

    return Array.from(userMap.values())
      .sort((a, b) => b.commentCount - a.commentCount)
  }

  /**
   * 计算用户角色分布
   */
  private calculateUserRoles(): DiscussionUserRolesDistribution {
    const roles: DiscussionUserRolesDistribution = {
      [DiscussionUserRole.OriginalPoster]: 0,
      [DiscussionUserRole.Author]: 0,
      [DiscussionUserRole.Admin]: 0,
      [DiscussionUserRole.RegularUser]: 0,
      [DiscussionUserRole.DeletedUser]: 0,
    }

    this.commentsData.forEach((comment) => {
      roles[comment.role]++
    })

    return roles
  }

  /**
   * 计算时间分布
   */
  private calculateTimeDistribution(comments?: DiscussionCommentData[]): DiscussionTimeDistribution {
    const distribution: DiscussionTimeDistribution = {
      byHour: {},
      byDay: {},
      byWeekday: Array.from<number>({ length: 7 }).fill(0),
    }

    const dataSource = comments || this.commentsData

    dataSource.forEach((comment) => {
      const date = new Date(comment.timestampMs)
      const day = date.toDateString()
      const weekday = (date.getDay() + 6) % 7 // 从周一开始，0表示周一

      distribution.byDay[day] = (distribution.byDay[day] || 0) + 1
      distribution.byWeekday[weekday]++
    })

    distribution.byHour = ToolKit.time.extractHourDistribution(dataSource.map(comment => comment.timestampMs))
    return distribution
  }

  /**
   * 计算按角色分类的数据
   */
  private calculateRoleBasedData(): DiscussionRoleBasedData {
    const roleBasedData: DiscussionRoleBasedData = {}

    // 为每个角色计算数据
    Object.values(DiscussionUserRole).forEach((role) => {
    // 筛选该角色的评论
      const roleComments = this.commentsData.filter(comment => comment.role === role)

      if (roleComments.length === 0) {
        return
      }

      // 计算该角色的时间分布
      const timeDistribution = this.calculateTimeDistribution(roleComments)

      // 计算该角色的活动高峰
      const activityPeaks = this.calculateActivityPeaks(roleComments)

      roleBasedData[role] = {
        timeDistribution,
        activityPeaks,
        commentCount: roleComments.length,
        userCount: new Set(roleComments.map(c => c.user.name)).size,
      }
    })

    return roleBasedData
  }

  /**
   * 计算活动高峰
   */
  private calculateActivityPeaks(comments?: DiscussionCommentData[]): Array<{ hour: number, count: number }> {
    const hourlyCounts = this.calculateTimeDistribution(comments).byHour
    return Object.entries(hourlyCounts)
      .map(([hour, count]) => ({ hour: Number(hour.replace(':00', '')), count }))
      .sort((a, b) => b.count - a.count)
      .slice(0, 5)
  }

  /**
   * 计算时间分析指标
   */
  private calculateTimeMetrics(): DiscussionTimeMetrics {
    if (this.commentsData.length === 0) {
      return {
        averageInterval: 0,
        maxInterval: 0,
        minInterval: 0,
        slowestCommentId: '',
        fastestCommentId: '',
        firstCommentTime: '',
        lastCommentTime: '',
        hoursSinceLastUpdate: 0,
        commentFrequency: 0,
        isActive: false,
        activityLevel: DiscussionActivityLevel.Low,
      }
    }

    // 获取时间戳并排序
    const timestamps = this.commentsData.map(c => c.timestampMs).sort()
    const firstTime = timestamps[0]
    const lastTime = timestamps[timestamps.length - 1]

    // 计算平均发布间隔
    const intervals = this.calculateCommentIntervals(timestamps)
    const averageInterval = this.calculateAverageInterval(intervals, firstTime, lastTime)
    const { maxInterval, minInterval, slowestCommentId, fastestCommentId } = this.calculateExtremeReplyComments(intervals)

    // 计算多久没更新
    const now = Date.now()
    const hoursSinceLastUpdate = (now - lastTime) / TIME_UNITS.COMMON.INTERVALS.ONE_HOUR

    // 计算评论频率（条/天）
    const commentFrequency = this.calculateCommentFrequency(timestamps, firstTime, lastTime)

    // 判断活跃度
    const isActive = hoursSinceLastUpdate <= 24
    const activityLevel = this.calculateActivityLevel(hoursSinceLastUpdate, commentFrequency)

    return {
      averageInterval: Number(averageInterval.toFixed(1)),
      maxInterval: Number(maxInterval.toFixed(1)),
      minInterval: Number(minInterval.toFixed(1)),
      slowestCommentId,
      fastestCommentId,
      firstCommentTime: new Date(firstTime).toISOString(),
      lastCommentTime: new Date(lastTime).toISOString(),
      hoursSinceLastUpdate: Math.round(hoursSinceLastUpdate * 10) / 10,
      commentFrequency: Math.round(commentFrequency * 100) / 100,
      isActive,
      activityLevel,
    }
  }

  /**
   * 计算评论之间的时间间隔（以分钟为单位）
   * @param {number[]} timestamps - 排序后的时间戳数组
   * @returns {number[]} 时间间隔数组（分钟）
   */
  private calculateCommentIntervals(timestamps: number[]): number[] {
    if (timestamps.length <= 1) {
      return [0] // 只有一条评论时，间隔为0
    }

    const intervals: number[] = []

    for (let i = 1; i < timestamps.length; i++) {
      const intervalMs = timestamps[i] - timestamps[i - 1]
      const intervalMinutes = intervalMs / TIME_UNITS.COMMON.INTERVALS.ONE_MINUTE
      intervals.push(intervalMinutes)
    }

    logger.debug(`[${this.name}] 计算时间间隔`, {
      totalIntervals: intervals.length,
      intervals: intervals.map(i => i.toFixed(2)),
    })

    return intervals
  }

  /**
   * 计算平均时间间隔
   * @param {number[]} intervals - 时间间隔数组
   * @param {number} firstTime - 第一条评论时间戳
   * @param {number} lastTime - 最后一条评论时间戳
   * @returns {number} 平均间隔（天）
   */
  private calculateAverageInterval(intervals: number[], firstTime: number, lastTime: number): number {
    if (intervals.length === 0) {
      return 0
    }

    // 方法1：使用间隔数组计算平均值（更准确反映实际发布模式）
    const sumIntervals = intervals.reduce((sum, interval) => sum + interval, 0)
    const averageFromIntervals = sumIntervals / intervals.length

    // 方法2：使用总时间跨度计算（更反映整体频率）
    const totalDurationDays = (lastTime - firstTime) / TIME_UNITS.COMMON.INTERVALS.ONE_HOUR
    const averageFromDuration = this.commentsData.length > 1
      ? totalDurationDays / (this.commentsData.length - 1)
      : 0

    // 选择更合理的平均值（当评论数量较少时，使用间隔平均值更准确）
    const averageInterval = intervals.length >= 3 ? averageFromIntervals : averageFromDuration

    logger.debug(`[${this.name}] 平均间隔计算`, {
      intervalCount: intervals.length,
      averageFromIntervals: averageFromIntervals.toFixed(2),
      averageFromDuration: averageFromDuration.toFixed(2),
      finalAverage: averageInterval.toFixed(2),
    })

    return averageInterval
  }

  /**
   * 计算回复评论最大最小时间间隔以及对应的评论 ID
   * @param {number[]} intervals - 时间间隔数组
   * @returns {object} 包含最大和最小间隔的对象
   */
  private calculateExtremeReplyComments(intervals: number[]): {
    maxInterval: number
    minInterval: number
    fastestCommentId: string
    slowestCommentId: string
  } {
    if (intervals.length === 0) {
      return { maxInterval: 0, minInterval: 0, fastestCommentId: '', slowestCommentId: '' }
    }

    let maxInterval = intervals[0]
    let minInterval = intervals[0]
    let fastestCommentId = ''
    let slowestCommentId = ''

    intervals.forEach((interval, index) => {
      if (interval > maxInterval) {
        maxInterval = interval
        slowestCommentId = this.commentsData[index + 1].id
      }
      if (interval < minInterval) {
        minInterval = interval
        fastestCommentId = this.commentsData[index + 1].id
      }
    })

    // 特殊处理：如果只有一条评论，间隔为0
    if (this.commentsData.length === 1) {
      maxInterval = 0
      minInterval = 0
      fastestCommentId = ''
      slowestCommentId = ''
    }

    logger.debug(`[${this.name}] 最大最小间隔计算`, {
      maxInterval: maxInterval.toFixed(2),
      minInterval: minInterval.toFixed(2),
      intervalRange: (maxInterval - minInterval).toFixed(2),
      slowestCommentId,
      fastestCommentId,
    })

    return { maxInterval, minInterval, fastestCommentId, slowestCommentId }
  }

  /**
   * 计算评论频率
   * @param {number[]} timestamps - 时间戳数组
   * @param {number} firstTime - 第一条评论时间
   * @param {number} lastTime - 最后一条评论时间
   * @returns {number} 评论频率（条/天）
   */
  private calculateCommentFrequency(timestamps: number[], firstTime: number, lastTime: number): number {
    if (timestamps.length === 0) {
      return 0
    }

    const totalDurationMs = lastTime - firstTime
    const totalDurationDays = totalDurationMs / TIME_UNITS.COMMON.INTERVALS.ONE_DAY

    // 避免除以0的情况
    if (totalDurationDays <= 0) {
      return timestamps.length // 如果时间跨度为0，频率等于评论数量
    }

    const frequency = timestamps.length / totalDurationDays

    logger.debug(`[${this.name}] 评论频率计算`, {
      totalDurationDays: totalDurationDays.toFixed(2),
      commentCount: timestamps.length,
      frequency: frequency.toFixed(2),
    })

    return frequency
  }

  /**
   * 计算活跃度等级
   */
  private calculateActivityLevel(hoursSinceUpdate: number, frequency: number): DiscussionActivityLevel {
    if (hoursSinceUpdate <= 6 && frequency >= 2)
      return DiscussionActivityLevel.High

    if (hoursSinceUpdate <= 24 && frequency >= 0.5)
      return DiscussionActivityLevel.Medium

    return DiscussionActivityLevel.Low
  }

  /**
   * 计算最活跃用户
   */
  private calculateMostActiveUser(userStats: DiscussionUserStats[]): DiscussionUserStats | null {
    if (userStats.length === 0) {
      return null
    }

    const regularUserStats = userStats.filter(u => u.role === DiscussionUserRole.RegularUser)

    if (regularUserStats.length === 0) {
      return null
    }

    return regularUserStats.reduce((prev, current) => {
      // 首先比较评论数量
      if (prev.commentCount !== current.commentCount) {
        return prev.commentCount > current.commentCount ? prev : current
      }

      // 评论数量相同时，取 firstCommentTime 最早的（最先参与讨论的）
      return prev.firstCommentTime < current.firstCommentTime ? prev : current
    })
  }

  /**
   * 计算讨论持续时间
   */
  private calculateDiscussionDuration(): DiscussionDuration {
    if (this.commentsData.length === 0) {
      return { start: '', end: '', durationHours: 0 }
    }

    const timestamps = this.commentsData.map(c => c.timestampMs).sort()
    const start = new Date(timestamps[0])
    const end = new Date(timestamps[timestamps.length - 1])
    const durationHours = (end.getTime() - start.getTime()) / TIME_UNITS.COMMON.INTERVALS.ONE_HOUR

    return {
      start: start.toISOString(),
      end: end.toISOString(),
      durationHours,
    }
  }

  applyConfig(config: Partial<Config>): void {
    super.updateConfig(config)

    this.setupAnalysis()

    logger.info(`[${this.name}] Config updated and apply`, this.config)
  }

  getStyles(): string {
    return `
#${this.BUTTON_ID} {
  background-color: transparent !important;
  border: none !important;
  color: var(${this.themeVarService.link.default.text}) !important;
  
  &:hover {
    color: var(${this.themeVarService.link.default.textHover}) !important;
  }
}

.${this.uiService.DASHBOARD_ID} {
  position: fixed;
  top: 0;
  left: 0;
  width: 500px;
  max-height: 90vh;
  background: var(${this.themeVarService.default.background.list});
  border: 1px solid var(${this.themeVarService.default.border.colorNeutral});
  border-radius: 12px;
  border-top-left-radius: 0;
  border-bottom-left-radius: 0;
  z-index: 10000;
  
  .dashboard-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px 20px;
    background: transparent;
    border-bottom: 1px solid var(${this.themeVarService.default.border.colorNeutral});
    
    h3 {
      margin: 0;
      font-size: 16px;
      font-weight: 600;
      color: var(${this.themeVarService.default.text.primary});
    }
    
    .dashboard-controls {
      display: flex;
      gap: 8px;
      
      ${BUTTON_TEMPLATE_STYLES.close}
    }
  }
  
  .dashboard-content {
    padding: 20px;
    max-height: calc(80vh - 80px);
    overflow-y: auto;
    
    .base-info {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 12px;
      
      .post-time, .comment-frequency {
        font-size: 12px;
        color: var(${this.themeVarService.default.text.secondary});
      }
    }
    
    .summary-cards {
      display: grid;
      grid-template-columns: repeat(3, 1fr);
      gap: 12px;
      margin-bottom: 20px;
      
      .summary-card {
        background: transparent;
        border: 1px solid var(${this.themeVarService.default.border.colorNeutral});
        border-radius: 8px;
        padding: 12px;
        text-align: center;
        
        &.overview-card {
          grid-column: 1 / -1;
          grid-row: auto;
          
          .heat-section {
            margin-bottom: 16px;
            
            .heat-circle {
              width: 80px;
              height: 80px;
              border: 3px solid;
              border-radius: 50%;
              display: flex;
              flex-direction: column;
              align-items: center;
              justify-content: center;
              margin: 0 auto 8px;
              background: var(${this.themeVarService.default.background.list});
              transition: all 0.3s ease;
              
              .heat-score {
                font-size: 18px;
                font-weight: 700;
              }
            }
          }
          
          .metrics-flex {
            display: flex;
            gap: 5px;
            justify-content: center;
            
            .metric-item {
              display: flex;
              align-items: center;
              gap: 8px;
              
              .metric-icon {
                font-size: 16px;
                opacity: 0.8;
              }
              
              .metric-value {
                font-size: 16px;
                font-weight: 600;
                color: var(${this.themeVarService.default.text.primary});
                line-height: 1.2;
              }
            }
          }
          
          .update-status {
            font-size: 12px;
            color: #747d8c;
          }
        }
        
        &[data-action="fastest-reply"], &[data-action="slowest-reply"] {
          position: relative;
          
          &:hover {
            .card-label {
              color: var(${this.themeVarService.link.default.text});
            }
          }
        }
        
        .card-icon {
          font-size: 20px;
          margin-bottom: 4px;
        }
        
        .card-content {
          .card-value {
            font-size: 18px;
            font-weight: 600;
            color: var(${this.themeVarService.default.text.primary});
          }
          
          .card-label {
            font-size: 11px;
            color: var(${this.themeVarService.default.text.secondary});
            margin-top: 2px;
          }
        }
      }
    }
  }
  
  .charts-container {
    .user-ranking-section,
    .time-distribution-section {
      margin-bottom: 20px;
      
      h4 {
        margin: 0 0 12px 0;
        font-size: 15px;
        font-weight: 600;
        color: var(${this.themeVarService.default.text.primary});
      }
    }
    
    .user-ranking-section {
      .user-ranking-list {
        display: flex;
        flex-direction: column;
        gap: 8px;
        
        .user-ranking-item {
          display: flex;
          align-items: center;
          gap: 12px;
          padding: 8px;
          background: transparent;
          border-radius: 6px;
          
          .user-rank {
            font-weight: 600;
            color: var(${this.themeVarService.default.text.secondary});
            min-width: 24px;
          }

          .user-avatar img {
            width: 24px;
            height: 24px;
            border-radius: 50%;
            object-fit: cover;
          }

          .user-info {
            flex: 1;
            
            .user-name {
              font-size: 13px;
              font-weight: 500;
              color: var(${this.themeVarService.default.text.primary});
            }

            .user-role {
              font-size: 11px;
              color: var(${this.themeVarService.default.text.secondary});
            }
          }
          
          .user-stats {
            font-size: 12px;
            font-weight: 600;
            color: var(${this.themeVarService.default.text.primary});
          }
        }
      }
    }
    
    .time-distribution-section {
      .custom-select {
        margin-bottom: 8px !important;
      }
    }
  }
}
`
  }
}
